package com.gitee.mall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 创建对应的交换器  队列  路由绑定规则
 */
@Configuration
public class MyMQConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 库存释放交换器
     *
     * @return
     */
    @Bean
    public Exchange orderEventExchange() {
        return ExchangeBuilder.topicExchange("stock-event-exchange").durable(true).build();
    }

    /**
     * 库存释放 死信队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");              //将死信消息交给那个死信交换机
        arguments.put("x-dead-letter-routing-key", "stock.release");                 //信息消息路由规则
        arguments.put("x-message-ttl", 60000);                                        //消息死信时长
        return QueueBuilder.durable("stock.delay.queue").withArguments(arguments).build();
    }

    /**
     * 库存释放队列
     *
     * @return
     */
    @Bean
    public Queue stockReleaseQueue() {
        return QueueBuilder.durable("stock.release.stock.queue").build();
    }

    /**
     * 锁定库存 进入锁定库存死信队列
     *
     * @return
     */
    @Bean
    public Binding stockDelayBinding() {
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked",
                null);
    }

    /**
     * 释放库存
     *
     * @return
     */
    @Bean
    public Binding stockReleaseBinding() {
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }
}
